/*============= 客户端代码 client.c ==============*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>

#define BUFFER_SIZE 1024
#define SERVER_IP "192.168.1.72"

#define PORT 8888

int sock;
char username[32];

void *receive_handler(void *arg) {
    char buffer[BUFFER_SIZE];
    while(1) {
        int receive_size = recv(sock, buffer, BUFFER_SIZE, 0);
        if (receive_size <= 0) {
            printf("\nDisconnected from server\n");
            exit(EXIT_FAILURE);
        }
        buffer[receive_size] = '\0';
        printf("%s", buffer);
    }
}

int main() {
    struct sockaddr_in server_addr;
    
    // 创建socket
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Socket creation failed");
        exit(EXIT_FAILURE);
    }
    
    // 设置服务器地址
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    if (inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr) <= 0) {
        perror("Invalid address");
        exit(EXIT_FAILURE);
    }
    
    // 连接服务器
    if (connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("Connection failed");
        exit(EXIT_FAILURE);
    }
    
    // 获取用户名
    printf("请输入用户名: ");
    fgets(username, 32, stdin);
    username[strcspn(username, "\n")] = '\0'; // 去除换行符
    send(sock, username, strlen(username), 0);
    
    printf("连接到服务器，输入消息开始聊天（输入exit退出）\n");
    
    // 创建接收线程
    pthread_t receive_thread;
    if (pthread_create(&receive_thread, NULL, receive_handler, NULL) != 0) {
        perror("Thread creation failed");
        exit(EXIT_FAILURE);
    }
    
    // 处理用户输入
    char message[BUFFER_SIZE];
    while(1) {
        fgets(message, BUFFER_SIZE, stdin);
        if (strcmp(message, "exit\n") == 0) {
            printf("退出中...\n");
            break;
        }
        send(sock, message, strlen(message), 0);
    }
    
    close(sock);
    return 0;
}
